package com.example.ribbonconsumer.config;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
* @desc   全局异常处理类
* @author kanggw
* @datetime 2021/9/17,5:15 下午
*/
public class GlobalHandlerExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse resp
            , Object o, Exception ex) {

        if (ex instanceof BusinessException) {
            //AthenaException为一个自定义异常
            ex.printStackTrace();
            printWrite(ex.toString(), resp);
            return new ModelAndView();
        } else {

            printWrite(ex.getMessage(),resp);
        }


        return new ModelAndView();
    }


    /**
     * 将错误信息添加到response中
     *
     * @param msg
     * @param response
     * @throws
     */
    public static void printWrite(String msg, HttpServletResponse response) {

        PrintWriter out = null;

        try {
            out = response.getWriter();
            out.write(msg);
            out.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (null != out) {
                out.close();
            }
        }
    }
}
